package com.xavier.config.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.xavier.annotation.PassLogin;
import com.xavier.result.Result;
import com.xavier.result.ResultCode;
import com.xavier.utils.UserContainer;
import com.xavier.utils.UserUtil;
import com.xavier.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户拦截器
 */
@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        try {
            log.info("requestUri：{},contextPath：{},parameterNames：{}", request.getRequestURI(), request.getContextPath(), JSON.toJSONString(request.getParameterMap()));

            if (!supports(handler)) {
                return true;
            }
            UserInfoVO userInfo = UserUtil.getUserInfo();
            if (ObjectUtil.isEmpty(userInfo)) {
                returnErrorJson(response, JSON.toJSONString(Result.error(ResultCode.C600)));
                return false;
            }
            UserUtil.expire(userInfo);
            UserContainer.set(userInfo);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            returnErrorJson(response, JSON.toJSONString(Result.error(ResultCode.SYS_ERROR)));
            return false;
        }

    }


    /**
     * 是否拦截
     *
     * @return {@code boolean} 拦截，不拦截
     */
    private boolean supports(Object object) {
        if (object instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) object;
            return method.getMethodAnnotation(PassLogin.class) == null;
        }
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContainer.remove();
    }


    public void returnErrorJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
